package com.isoftstone.merchant.controller.payment;

import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Page;
import com.isoftstone.common.Tidings;
import com.isoftstone.merchant.entity.feeUser.MFeeUser;
import com.isoftstone.merchant.entity.mdept.MDept;
import com.isoftstone.merchant.entity.notify.BNotify;
import com.isoftstone.merchant.entity.notify.BNotifyDetail;
import com.isoftstone.merchant.entity.payment.Payment;
import com.isoftstone.merchant.service.feeUser.FeeUserService;
import com.isoftstone.merchant.service.mdept.IMdeptService;
import com.isoftstone.merchant.service.mproject.MProjectService;
import com.isoftstone.merchant.service.mprojecttype.MProjectTypeService;
import com.isoftstone.merchant.service.notice.INotifyService;
import com.isoftstone.merchant.service.payment.IMPaymentDetialService;
import com.isoftstone.merchant.service.payment.PaymentService;
import com.isoftstone.util.Const;
import com.isoftstone.util.ObjectExcelView;
import com.isoftstone.util.PageData;
import com.isoftstone.util.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PaymentController extends BaseController {
    @Autowired
    FeeUserService feeUserService;
    @Autowired
    IMdeptService mdeptService;
    @Autowired
    MProjectTypeService mProjectTypeService;
    @Autowired
    MProjectService mProjectService;
    @Autowired
    PaymentService paymentService;
    @Autowired
    IMPaymentDetialService imPaymentDetialServicec;
    @Autowired
    INotifyService notifyService;

    /*
    * to收费查询列表
    * */
    @RequiresPermissions("mms-menu.003.005")
    @RequestMapping("/merchant/payment/togetFeeUserList")
    public ModelAndView togetFeeUserList(Page page) {
        ModelAndView md=new ModelAndView();
        md.setViewName("merchant/charge_management/charge_inquiry");
        return md;
    }
    /*
    * 收费查询列表
    * */
    @RequestMapping("/merchant/payment/getFeeUserList")
    @ResponseBody
    public Object getFeeUserList(Page page) {
        Tidings<List<Payment>> tidings=new Tidings<List<Payment>>();
        PageData pd = this.getPageData();
        String corpId=this.getUser().getCorpId();
        String userId=this.getUser().getUserid();
        List<MDept>deptids=null;
        try {
            deptids=feeUserService.getalldeptByUserId(userId);//得到用户对应的deptid
            if(deptids!=null){
                List<String>list=new ArrayList<String>();
                for(MDept mDept1:deptids){
                    list.add(mDept1.getDeptId());
                }
                pd.put("deptIds",list);//看到当前用户部门的缴费用户
            }
            String treeId = pd.getString("treeId");
            String projectTypeId = pd.getString("projectTypeInfo");
            String projectId = pd.getString("projectInfo");
            String searchContext = pd.getString("feeUserName");
            String payStatus = pd.getString("payStatus");
            String beginDate = pd.getString("beginDate");
            String endDate = pd.getString("endDate");
            //导出参数同查询参数
            this.getSession().setAttribute("treeId",treeId);
            this.getSession().setAttribute("projectTypeId",projectTypeId);
            this.getSession().setAttribute("projectId",projectId);
            this.getSession().setAttribute("searchContext",searchContext);
            this.getSession().setAttribute("payStatus",payStatus);
            this.getSession().setAttribute("beginDate",beginDate);
            this.getSession().setAttribute("endDate",endDate);

            //判断前台传过来的数据是否为空，并保存
            //pd.put("projectTypeId",((projectTypeId == null)?"":projectTypeId));
            pd.put("projectId",((projectId == null)?"":projectId));

            if (searchContext != null) {
                searchContext = URLDecoder.decode(searchContext, "UTF-8");
                pd.put("searchContext",((searchContext == null)?"":searchContext));
            }

            pd.put("payStatus",((payStatus == null)?"":payStatus));
            pd.put("beginDate",((beginDate == null)?"":beginDate));
            pd.put("endDate",((endDate == null)?"":endDate));
            pd.put("corpId",corpId);
            pd.put("status","1");//生效的缴费信息
            List<Payment> paymentSearch = new ArrayList<Payment>();
            List<Payment> parmentList = new ArrayList<Payment>();
            List<String >treeIdss=new ArrayList<String>();
            //机构有多个，每一个都进行遍历，其他只需判空即可
            if (StringUtils.isNotBlank(treeId)) {
                String treeIds[] = treeId.split(",");
                for (String str : treeIds) {
                    treeIdss.add(str);
                }
                pd.put("treeids",treeIdss);
                page.setPd(pd);
                parmentList = paymentService.getmFeeUserlistPage(page);
            }else{
                page.setPd(pd);
                paymentSearch = paymentService.getmFeeUserlistPage(page);
                if (paymentSearch != null) {
                    for (Payment payment : paymentSearch) {
                        parmentList.add(payment);
                    }
                }
            }

            tidings.setT(parmentList).setPage(page);
            tidings.setStatus(Const.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            tidings.setStatus(Const.ERROR);
        }
        return tidings;
    }

    /*
    * 收费查询删除
    * */
    @RequestMapping("/merchant/payment/deleteFormPayment")
    @ResponseBody
    public Object deleteFormPayment(Long payId,Long projectId){
        Tidings<String> tidings = new Tidings<String>();
        try{
            Payment payment=paymentService.getPaymentByPayId(payId);
            Map<String ,Object>map=new HashMap<String,Object>();
            map.put("payId",payId);
            map.put("feeUserId",payment.getFeeUserId());
           List <BNotifyDetail> bNotifyDetail=notifyService.getNotifyByPayIdAndfeeUserID(map);
            for(BNotifyDetail bNotifyDetail1:bNotifyDetail){
                notifyService.deleteNotify(bNotifyDetail1.getNotify_id());//删除通知表数据
            }
            notifyService.deletenotifyFromDetail(map);//删除通知细节表数据
            imPaymentDetialServicec.deleteFormPaymentDetail(payId,projectId);
            paymentService.deleteFormPayment(payId);
            tidings.setStatus(Const.SUCCESS);
            tidings.setMsg("删除成功！");
        }catch(Exception e){
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("删除失败！");
            e.printStackTrace();
        }

        return tidings;
    }

    /*
   * 撤回
   * */
    @RequestMapping("/merchant/payment/recall")
    @ResponseBody
    public Object recall(){
        Tidings<String> tidings = new Tidings<String>();
        PageData pd = this.getPageData();
        String payId=pd.getString("payId");
        Payment payment=new Payment();
        String status="0";//状态设置为失效
        payment.setStatus(status);
        payment.setPayId(Long.parseLong(payId));
        try{
            paymentService.updatePaymentStatus(payment);
            tidings.setStatus(Const.SUCCESS);
            tidings.setMsg("撤回成功！");
        }catch(Exception e){
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("撤回失败！");
            e.printStackTrace();
        }

        return tidings;
    }

    /*
    * 催缴
    * */
    @RequestMapping("/merchant/payment/reminderFeeUser")
    @ResponseBody
    public Object reminderFeeUser(Long payId,Long projectId,String projectName,String feeUserId){
        Tidings<String> tidings = new Tidings<String>();
        try{
            MFeeUser feeUser = feeUserService.getFeeUserById(feeUserId);
            //修改m_payment_main中催缴次数+1，并通知客户缴费
            //先查后改
            Payment payment = paymentService.getPaymentById(payId,projectId);
            payment.setPayId(payment.getPayId());
            if (payment.getUrgeCnt() != null) {
                payment.setUrgeCnt(payment.getUrgeCnt()+1);
            }else{
                payment.setUrgeCnt(1);
            }
            //修改催缴次数
            paymentService.editUrgeCnt(payment);
            String nickname = this.getUser().getNickname();
            //发通知
            BNotify bNotify = new BNotify();
            bNotify.setNotifyContext("您的缴费项" + projectName + "未缴费，缴费编号为"+ feeUser.getFeeId()+",请尽快缴纳！");
            bNotify.setNotifyType("0001");
            bNotify.setPhoneType(Const.n0003);
            bNotify.setCreatorType("02");
            bNotify.setStatus(Const.send);
            bNotify.setCreateDate(new Date());
            bNotify.setCreator(nickname);//当前登录用户

            BNotifyDetail bNotifyDetail = new BNotifyDetail();
            bNotifyDetail.setUser_type("03");
            bNotifyDetail.setPay_id(payId);
            bNotifyDetail.setIs_read("0");//新增时设置消息未读

            notifyService.reminderNotify(bNotifyDetail,bNotify,feeUserId);
            tidings.setStatus(Const.SUCCESS);
            tidings.setMsg("催缴成功！");
        }catch(Exception e){
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("催缴失败！");
            e.printStackTrace();
        }
        return tidings;
    }

    /*
    * 批量导出
    * */
    @RequestMapping("/merchant/payment/exportToExcel")
    public ModelAndView exportToExcel() {
        ModelAndView mv = new ModelAndView();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("缴费流水号");
        titles.add("缴费人员");
        titles.add("机构");
        titles.add("收费项目");
        titles.add("应缴金额");
        titles.add("实缴金额");
        titles.add("支付流水号");
        titles.add("缴费时间");
        titles.add("缴费状态");
        titles.add("缴费方式");
        titles.add("收费人");
        dataMap.put("titles", titles);
        List<PageData> subList = new ArrayList<PageData>();
        try {
            //取出查询时保存在session中的参数
            String treeId= (String) this.getSession().getAttribute("treeId");
            String projectTypeId= (String) this.getSession().getAttribute("projectTypeId");
            String projectId= (String) this.getSession().getAttribute("projectId");
            String searchContext= (String) this.getSession().getAttribute("searchContext");
            String payStatus= (String) this.getSession().getAttribute("payStatus");
            String beginDate= (String) this.getSession().getAttribute("beginDate");
            String endDate= (String) this.getSession().getAttribute("endDate");
            Payment payments = new Payment();
            if(!projectTypeId.equals("")){
                payments.setProjectTypeId(Long.parseLong(projectTypeId));
            }
            if(!projectId.equals("")){
                payments.setProjectId(Long.parseLong(projectId));
            }
            payments.setFeeuUserName((searchContext.equals(""))?"":searchContext);
            payments.setPayStatus((payStatus.equals(""))?"":payStatus);
            payments.setBeginDate((beginDate == null)?"":beginDate);
            payments.setEndDate((endDate == null)?"":endDate);
            payments.setCorpId(this.getUser().getCorpId());//商户ID
            payments.setStatus("1");//生效的缴费用户
            List<Payment> paymentSearch = new ArrayList<Payment>();
            List<Payment> parmentList = new ArrayList<Payment>();

            if (StringUtils.isNotBlank(treeId)) {
                String treeIds[] = treeId.split(",");
                for (String str : treeIds) {
                    payments.setDeptId(str);
                    paymentSearch = paymentService.getPaymentListByExport(payments);
                    if (paymentSearch != null) {
                        for (Payment payment : paymentSearch) {
                            parmentList.add(payment);
                        }
                    }
                }
            }else{
                String userId=this.getUser().getUserid();
                List<MDept>deptids=feeUserService.getalldeptByUserId(userId);//得到用户对应的deptid
                if(deptids!=null){
                    List<String>list=new ArrayList<String>();
                    for(MDept mDept1:deptids){
                        list.add(mDept1.getDeptId());
                    }
                    payments.setDeptIds(list);//看到当前用户部门的缴费用户
                }
                paymentSearch = paymentService.getPaymentListByExport(payments);
                if (paymentSearch != null) {
                    for (Payment payment : paymentSearch) {
                        parmentList.add(payment);
                    }
                }
            }

            for (Payment payment : parmentList) {
                PageData subpd = new PageData();
                if(payment.getPayId() != null){//缴费流水号
                    subpd.put("var1", payment.getPayId().toString());
                }else{
                    subpd.put("var1","");
                }
                subpd.put("var2", payment.getFeeUserName());
                subpd.put("var3", payment.getDeptName());//机构
                subpd.put("var4", payment.getProjectName());

                if(payment.getTotalAmt() != null){//应缴
                    subpd.put("var5", payment.getTotalAmt().toString());
                }else {
                    subpd.put("var5", "");
                }

                if(payment.getFactAmt() != null){//实缴
                    subpd.put("var6", payment.getFactAmt().toString());
                }else{
                    subpd.put("var6", "");
                }
                subpd.put("var7", payment.getPaySeq());//支付流水号

                if(payment.getPayDate() != null){//缴费日期
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String payDate = sdf.format(payment.getPayDate());
                    subpd.put("var8", payDate);
                }else{
                    subpd.put("var8", "");
                }
                if (StringUtils.isNotBlank(payment.getPayStatus()) && payment.getPayStatus().equals("04")) {
                    subpd.put("var9", "待缴费");
                }
                if (StringUtils.isNotBlank(payment.getPayStatus()) && payment.getPayStatus().equals("P-00")) {
                    subpd.put("var9", "已缴费");
                }
                if (StringUtils.isNotBlank(payment.getPayType()) && payment.getPayType().equals("01")) {
                    subpd.put("var10", "POS");
                }else if (StringUtils.isNotBlank(payment.getPayType()) && payment.getPayType().equals("02")) {
                    subpd.put("var10", "现金");
                }else{
                    subpd.put("var10", "");
                }
                subpd.put("var11", payment.getUpdator());//收费人
                subList.add(subpd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dataMap.put("varList", subList);
        dataMap.put("name", "paymentHistory_");
        dataMap.put("sheetName", "历史交易记录查询");
        ObjectExcelView oev = new ObjectExcelView();
        mv = new ModelAndView(oev, dataMap);
        return mv;
    }


    /*
    * 统计交易总数
    * */
    @RequestMapping("merchant/payment/getPayUserNumber")
    @ResponseBody
    public Object getPayUserNumber(Page page){
        Tidings<Object> tidings=new Tidings<Object>();
        PageData pd = this.getPageData();
        String startDate=pd.getString("startDate");//开始时间
        String endDate=pd.getString("endDate");//结束时间
        Date createDate=new Date();
        pd.put("createDate",createDate);//当前时间
        if (StringUtils.isNotBlank(startDate)){
            pd.put("beginDate",startDate);
        }
        if(StringUtils.isNotBlank(endDate)){
            pd.put("endDate",endDate);
        }

        String payStatus="P-00";//支付状态04:待缴费；P-00：已缴费
        pd.put("payStatus",payStatus);
        page.setPd(pd);

        String corpId=this.getUser().getCorpId();
        pd.put("corpId",corpId);
        page.setPd(pd);
        try {
            Payment payment=paymentService.getPayUserNumber(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }

    /*
   * 统计所有交易总数
   * */
    @RequestMapping("merchant/payment/getAllPayNumber")
    @ResponseBody
    public Object getAllPayNumber(Page page){
        Tidings<Object> tidings=new Tidings<Object>();
        PageData pd = this.getPageData();
        String payStatus="P-00";//支付状态04:待缴费；P-00：已缴费
        pd.put("payStatus",payStatus);
        page.setPd(pd);
        String corpId=this.getUser().getCorpId();
        pd.put("corpId",corpId);
        page.setPd(pd);
        try {
            Integer Number=paymentService.getAllPayNumber(page);
            tidings.setT(Number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }

    /*
   * 统计当天交易数
   * */
    @RequestMapping("merchant/payment/getTodayPayNumber")
    @ResponseBody
    public Object getTodayPayNumber(Page page){
        Tidings<Object> tidings=new Tidings<Object>();
        PageData pd = this.getPageData();
        Date createDate=new Date();
        pd.put("beginDate",createDate);//当前时间
        String payStatus="P-00";//支付状态04:待缴费；P-00：已缴费
        pd.put("payStatus",payStatus);
        String corpId=this.getUser().getCorpId();
        pd.put("corpId",corpId);
        page.setPd(pd);
        try {
            Integer Number=paymentService.getTodayPayNumber(page);
            tidings.setT(Number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }

    /*
  * 统计总交易金额
  * */
    @RequestMapping("merchant/payment/getAllPayMoney")
    @ResponseBody
    public Object getAllPayMoney(Page page){
        Tidings<Object> tidings=new Tidings<Object>();
        PageData pd = this.getPageData();
        String payStatus="P-00";//支付状态04:待缴费；P-00：已缴费
        pd.put("payStatus",payStatus);
        page.setPd(pd);
        String corpId=this.getUser().getCorpId();
        pd.put("corpId",corpId);
        page.setPd(pd);
        try {
            Double Number=paymentService.getAllPayMoney(page);
            if(Number==null){
                Number=0.0;
            }
            tidings.setT(Number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }

    /*
   * 统计当天交易金额
   * */
    @RequestMapping("merchant/payment/getTodayPayMoney")
    @ResponseBody
    public Object getTodayPayMoney(Page page){
        Tidings<Object> tidings=new Tidings<Object>();
        PageData pd = this.getPageData();
        Date createDate=new Date();
        pd.put("beginDate",createDate);//当前时间
        String payStatus="P-00";//支付状态04:待缴费；P-00：已缴费
        pd.put("payStatus",payStatus);
        String corpId=this.getUser().getCorpId();
        pd.put("corpId",corpId);
        page.setPd(pd);
        try {
            Double Number=paymentService.getTodayPayMoney(page);
            if(Number==null){//如果Number等于Null    返回0
                Number=0.0;
            }
            tidings.setT(Number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }


    @RequestMapping("/merchant/count/")
    @ResponseBody
    public Object count(){
        Tidings<Map> tidings=new Tidings<Map>();
        PageData TodayPageDate = new PageData();//当天缴费金额
        PageData AllPageDate = new PageData();//所有缴费金额
        PageData AllUserPageDate = new PageData();//所有缴费用户
        PageData TodayUserPageDate = new PageData();//所有缴费用户
        PageData TodayNumberPageDate = new PageData();//当天交易数
        PageData AllNumberPageDate = new PageData();//所有交易数

        //统计当天金额
        Date createDate=new Date();
        TodayPageDate.put("beginDate",createDate);//当前时间
        String payStatus="P-00";//支付状态04:待缴费；P-00：已缴费
        TodayPageDate.put("payStatus",payStatus);
        String corpId=this.getUser().getCorpId();
        TodayPageDate.put("corpId",corpId);

        //统计所有金额
        AllPageDate.put("payStatus",payStatus);
        AllPageDate.put("corpId",corpId);
        Double TodayMoney= null;

        //统计所有缴费用户
        String status="1";//审批状态：1-生效 0-失效 2-审批中
        AllUserPageDate.put("status",status);
        AllUserPageDate.put("corpId",corpId);

        //统计当天缴费用户
        TodayUserPageDate.put("createDate",createDate);//当前时间
        TodayUserPageDate.put("status",status);
        TodayUserPageDate.put("corpId",corpId);

        //统计当天交易数
        TodayNumberPageDate.put("beginDate",createDate);//当前时间
        TodayNumberPageDate.put("payStatus",payStatus);
        TodayNumberPageDate.put("corpId",corpId);

        //统计所有交易数
        AllNumberPageDate.put("payStatus",payStatus);
        AllNumberPageDate.put("corpId",corpId);
        try {
            TodayMoney = paymentService.getTodayPayMoneys(TodayPageDate);//当天缴费金额
            Double AllMoney=paymentService.getAllMoney(AllPageDate);//所有缴费金额
            if(TodayMoney==null){//如果Number等于Null    返回0
                TodayMoney=0.0;
            }
            if(AllMoney==null){
                AllMoney=0.0;
            }

            Integer AllUser=feeUserService.getAllUserNumbers(AllUserPageDate);//所有缴费用户
            Integer TodayUser=feeUserService.getTodayUserNumbers(TodayUserPageDate);//当天缴费用户


            Integer TodayNumber=paymentService.getTodayPayNumbers(TodayNumberPageDate);//统计当天交易数
            Integer AllNumber=paymentService.getAllPayNumbers(AllNumberPageDate);//统计所有交易总数
            Map map=new HashMap();
            map.put("TodayMoney",TodayMoney);
            map.put("AllMoney",AllMoney);
            map.put("AllUser",AllUser);
            map.put("TodayUser",TodayUser);
            map.put("TodayNumber",TodayNumber);
            map.put("AllNumber",AllNumber);
            tidings.setT(map);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return tidings;
    }
}